/*
    input: '1,2,3,5,7,8,9,10,11,14,15,16';

    output: '1~3, 5, 7~8, 10~11, 14'
*/


function change(s) {
    if (s.length <= 1) return s;
    
    let arr = s.split(',').map(item => parseInt(item, 10));

    let temp = [], res = [];

    let i = 0;
    
    arr.forEach((item, index) => {
        if (index === 0) {
            temp[0] = [item];
        } else if (item - arr[index - 1] === 1) {
            temp[i].push(item);
        } else {
            temp[++i] = [item];
        }
    })

    temp.forEach((item) => {
        if (item.length === 1) {
            res.push(item[0]);
        } else {
            res.push(`${item[0]}~${item[item.length - 1]}`);
        };
    });

    return res.join(',');
};

console.log(change('1,2,3,5,7,8,9,10,11,14,15,16'))